package cn.wolfcode.exception;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 利用AOP 对控制器增强
 * 处理控制器出现的异常
 *
 * handlerMethod代表出现异常的处理方法
 */
@ControllerAdvice
public class HandlerControllerException {

    /**
     * @ExceptionHandler,代表当前方法是处理什么异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Object handlerException(RuntimeException e, HttpServletResponse response, HandlerMethod method) {
        e.printStackTrace(); //方便找到bug
        //判断有没有贴ResponseBody注解
        if (method.hasMethodAnnotation(ResponseBody.class)){
            String errorMsg = "操作失败,请联系管理员";
            //判断是否逻辑异常,如果是,直接用自己定义的异常错误信息
            if (e instanceof LogicException){
                errorMsg = e.getMessage();
            }
            JsonResult jsonResult = new JsonResult(false,errorMsg);
            response.setContentType("application/json;charset=utf-8");

            try {
                response.getWriter().print(JSON.toJSONString(jsonResult));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        }else {
            return "common/error";
        }
    }

    /**
     * 捕获没有授权的异常
     * @param e
     * @param response
     * @param method
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    public Object handlerException1(UnauthorizedException e, HttpServletResponse response, HandlerMethod method) {
        e.printStackTrace(); //方便找到bug
        //判断有没有贴ResponseBody注解
        if (method.hasMethodAnnotation(ResponseBody.class)){
            String errorMsg = "你没有权限操作";
            JsonResult jsonResult = new JsonResult(false,errorMsg);
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().print(JSON.toJSONString(jsonResult));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        }else {
            return "common/nopermission";
        }

    }

}
